package com.fishingwithme.android.ui.screens.my

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.navigation.NavController
import androidx.paging.LoadState
import coil.compose.rememberAsyncImagePainter
import com.fishingwithme.android.R
import com.fishingwithme.android.data.model.MyCircleDto
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.theme.AppDimensions


@Composable
fun MyCirclesTabContent(
    circles: androidx.paging.compose.LazyPagingItems<MyCircleDto>,
    navController: NavController
) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
    ) {
        // Handle empty state - ensure minimum height
        if (circles.itemCount == 0 && circles.loadState.refresh is LoadState.NotLoading) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(vertical = AppDimensions.SPACING_32),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = stringResource(R.string.no_data_available),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }

        // Loading states - ensure minimum height
        when {
            circles.loadState.refresh is LoadState.Loading -> {
                Box(
                    modifier = Modifier
                        .fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            }

            circles.loadState.append is LoadState.Loading -> {
                Box(
                    modifier = Modifier
                        .fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            }

            circles.loadState.refresh is LoadState.Error -> {
                val error = (circles.loadState.refresh as LoadState.Error).error
                Box(
                    modifier = Modifier
                        .fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = stringResource(R.string.error_load_failed),
                        color = MaterialTheme.colorScheme.error
                    )
                }
            }

            // Content with data
            else -> {
                Column(
                    modifier = Modifier.fillMaxSize()
                ) {
                    // Process items in chunks of 3 to simulate a 3-column grid
                    for (i in 0 until circles.itemCount step 3) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_2)
                        ) {
                            // First item
                            Box(modifier = Modifier.weight(1f)) {
                                circles[i]?.let { circle ->
                                    CircleItem(circle = circle, navController)
                                }
                            }

                            // Second item (if exists)
                            if (i + 1 < circles.itemCount) {
                                Spacer(modifier = Modifier.width(AppDimensions.SPACING_2))
                                Box(modifier = Modifier.weight(1f)) {
                                    circles[i + 1]?.let { circle ->
                                        CircleItem(circle = circle, navController)
                                    }
                                }
                            } else {
                                Spacer(modifier = Modifier.weight(1f))
                            }

                            // Third item (if exists)
                            if (i + 2 < circles.itemCount) {
                                Spacer(modifier = Modifier.width(AppDimensions.SPACING_2))
                                Box(modifier = Modifier.weight(1f)) {
                                    circles[i + 2]?.let { circle ->
                                        CircleItem(circle = circle, navController)
                                    }
                                }
                            } else {
                                Spacer(modifier = Modifier.weight(1f))
                            }
                        }

                        Spacer(modifier = Modifier.height(AppDimensions.SPACING_2))
                    }
                }
            }
        }
    }
}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun CircleItem(circle: MyCircleDto, navController: NavController) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable {
                val router = "${FishingNavigation.CIRCLE_MGR}?id=${circle.id}"
                navController.navigate(router)
            },
        shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_4),
        elevation = CardDefaults.cardElevation(defaultElevation = AppDimensions.CARD_ELEVATION_2)

    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .size(AppDimensions.ICON_SIZE_120)
        ) {
            // Background image (first picture)
            if (circle.pics.isNotEmpty()) {
                Image(
                    painter = rememberAsyncImagePainter(circle.pics[0]),
                    contentDescription = null,
                    modifier = Modifier.fillMaxSize(),
                    contentScale = ContentScale.Crop
                )
            } else {
                // Placeholder if no image
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(AppDimensions.SPACING_2),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = stringResource(R.string.no_image),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                }
            }

            // Overlay with semi-transparent background for text readability
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(AppDimensions.SPACING_8),
                verticalArrangement = Arrangement.SpaceBetween
            ) {
                // Top section with title
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(AppDimensions.SPACING_2)
                        .background(Color.Black.copy(alpha = 0.5f))
                ) {
                    Text(
                        text = circle.title,
                        style = MaterialTheme.typography.bodyMedium,
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(AppDimensions.SPACING_4)
                    )
                }

                // Bottom section with details
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(AppDimensions.SPACING_2)
                        .background(Color.Black.copy(alpha = 0.5f))
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(AppDimensions.SPACING_4)
                    ) {
                        // City and active status
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Text(
                                text = circle.city,
                                style = MaterialTheme.typography.bodySmall,
                                color = Color.White,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis,
                                modifier = Modifier.weight(1f)
                            )
                            Text(
                                text = if (circle.isActive == 1) stringResource(R.string.circle_active) else stringResource(
                                    R.string.circle_inactive
                                ),
                                style = MaterialTheme.typography.bodySmall,
                                color = if (circle.isActive == 1) Color.Green else Color.Red,
                                fontWeight = FontWeight.Bold,
                                maxLines = 1
                            )
                        }

                        // Maintenance status
                        Text(
                            text = when (circle.maintainStatus) {
                                2 -> stringResource(R.string.circle_creator_maintainer)
                                1 -> stringResource(R.string.circle_creator)
                                else -> stringResource(R.string.circle_maintainer)
                            },
                            style = MaterialTheme.typography.bodySmall,
                            color = Color.White,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis
                        )
                    }
                }
            }
        }
    }
}